<template>
    <div>
        <el-table :data="competitions.list" style="width: 100%">
            <el-table-column prop="id" label="ID" width="100" />
            <el-table-column prop="title" label="标题" width="200" />
            <el-table-column prop="organizer" label="主办方" width="200" />
            <el-table-column
                prop="registrationStartTime"
                label="报名开始时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="registrationEndTime"
                label="报名结束时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="competitionStartTime"
                label="比赛开始时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="competitionEndTime"
                label="比赛结束时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="createdAt"
                label="创建时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="updatedAt"
                label="更新时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column prop="category" label="类别" width="150" />
            <el-table-column prop="subCategory" label="具体下分类别" width="150" />
            <el-table-column prop="employeeNumber" label="添加人工号" width="150" />
            <el-table-column label="图片" width="200">
                <template v-slot="scope">
                    <img
                        v-if="scope.row.imageUrl"
                        :src="scope.row.imageUrl"
                        width="100"
                        height="100"
                        alt="竞赛图片"
                    />
                    <span v-else>无图片</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template v-slot="scope">
                    <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" @click="deleteCompetition(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="competitions.total"
            :page-size="competitions.pageSize"
            :current-page="competitions.pageNum"
            @current-change="handlePageChange"
        />

        <!-- 编辑活动对话框 -->
        <el-dialog title="编辑竞赛" v-model="editDialogVisible">
            <el-form :model="selectedCompetition" label-width="120px">
                <el-form-item label="标题">
                    <el-input v-model="selectedCompetition.title"></el-input>
                </el-form-item>
                <el-form-item label="主办方">
                    <el-input v-model="selectedCompetition.organizer"></el-input>
                </el-form-item>
                <el-form-item label="报名开始时间">
                    <el-date-picker v-model="selectedCompetition.registrationStartTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="报名结束时间">
                    <el-date-picker v-model="selectedCompetition.registrationEndTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="比赛开始时间">
                    <el-date-picker v-model="selectedCompetition.competitionStartTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="比赛结束时间">
                    <el-date-picker v-model="selectedCompetition.competitionEndTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="类别">
                    <el-input v-model="selectedCompetition.category" disabled></el-input>
                </el-form-item>
                <el-form-item label="具体下分类别">
                    <el-input v-model="selectedCompetition.subCategory"></el-input>
                </el-form-item>
                <el-form-item label="添加人工号">
                    <el-input v-model="selectedCompetition.employeeNumber"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <el-upload
                        :before-upload="handleBeforeUpload"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :show-file-list="false"
                    >
                        <el-button type="primary">上传图片</el-button>
                    </el-upload>
                    <img :src="imageUrl" width="200" height="200" alt="竞赛图片" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updateCompetition">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import service from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

const competitions = ref({
    pageNum: 1,
    pageSize: 10,
    totalPage: 1,
    total: 0,
    list: []
});

const editDialogVisible = ref(false);
const selectedCompetition = ref({});
const imageUrl = ref('');

const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const date = new Date(cellValue);
    if (isNaN(date.getTime())) return 'Invalid Date';
    const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
    };
    return new Intl.DateTimeFormat('zh-CN', options).format(date).replace(/\//g, '/');
};

const handleBeforeUpload = (file) => {
    const formData = new FormData();
    formData.append('file', file);
    service.post('/upload/image', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
    })
        .then(response => {
            handleUploadSuccess(response.data);
        })
        .catch(error => {
            handleUploadError(error);
        });
    return false;
};

const handleUploadSuccess = (response) => {
    if (response) {
        selectedCompetition.value.photoUrl = response;
        loadImage(response);
    }
};

const handleUploadError = (error) => {
    console.error('图片上传失败', error);
    ElMessage.error('图片上传失败，请重试');
};

const fetchCompetitions = async (pageNum = 1) => {
    try {
        const response = await service.get('/admin/activity/activitiesPage', {
            params: { pageNum, pageSize: competitions.value.pageSize }
        });
        const data = response.data;
        for (const competition of data.list) {
            if (competition.photoUrl) {
                competition.imageUrl = await loadImage1(competition.photoUrl);
            } else {
                competition.imageUrl = '';
            }
        }
        competitions.value = data;
    } catch (error) {
        console.error('获取活动数据失败', error);
    }
};

const showEditDialog = (competition) => {
    selectedCompetition.value = { ...competition };
    imageUrl.value = competition.photoUrl || '';
    editDialogVisible.value = true;
};

const updateCompetition = async () => {
    try {
        await service.put('/admin/activity/update', selectedCompetition.value);
        await fetchCompetitions(competitions.value.pageNum);
        editDialogVisible.value = false;
        ElMessage.success('活动信息更新成功');
    } catch (error) {
        console.error('更新活动信息失败', error);
        ElMessage.error('活动信息更新失败');
    }
};

const deleteCompetition = async (id) => {
    try {
        await ElMessageBox.confirm('确定删除该活动吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await service.delete(`/admin/activity/${id}`);
        await fetchCompetitions(competitions.value.pageNum);
        ElMessage.success('活动删除成功');
    } catch (error) {
        console.error('删除活动失败', error);
        ElMessage.error('活动删除失败');
    }
};

const loadImage = (imagePath) => {
    service.get(`/images/${imagePath}`, { responseType: 'blob' })
        .then(response => {
            imageUrl.value = URL.createObjectURL(response.data);
        })
        .catch(error => {
            console.error('图片加载失败', error);
            ElMessage.error('图片加载失败，请重试');
        });
};

const loadImage1 = async (imagePath) => {
    try {
        const response = await service.get(`/images/${imagePath}`, { responseType: 'blob' });
        return URL.createObjectURL(response.data);
    } catch (error) {
        console.error('图片加载失败', error);
        ElMessage.error('图片加载失败，请重试');
        return '';
    }
};

const handlePageChange = (pageNum) => {
    competitions.value.pageNum = pageNum;
    fetchCompetitions(pageNum);
};

onMounted(() => {
    fetchCompetitions();
});
</script>

<style scoped>
.el-pagination {
    margin-top: 20px;
    text-align: right;
}
</style>